package com.itsenpupulai.longlivetest;

import android.graphics.Path;
import android.util.Log;

import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.Callback;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * Created by Administrator on 2017/6/16.
 */

public class NetUtils {
    /**
     * @param object     获取类名称
     * @param postParams 私有参数
     * @param callback   回调
     */
    public static void post(final Object object, HashMap<String, Object> postParams, Callback callback) {
        long timeStamp = System.currentTimeMillis();
        HashMap<String, Object> params = new HashMap<>();

        String timestamp = new Date().getTime() + "";


        params.put("appkey", "1");
        params.put("format", "json");
        params.put("timestamp",timestamp);
        params.put("version", "2.0.1");
        params.put("apiversion", "V1");
        params.putAll(postParams);
//       以参数作为原料，生成sign成品

        Set<Map.Entry<String, Object>> strings = params.entrySet();
        ArrayList<Map.Entry<String, Object>> entryList = new ArrayList<>(strings);
        Collections.sort(entryList, new Comparator<Map.Entry<String, Object>>() {
            @Override
            public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) {
                String subO1 = o1.getKey().substring(0, 1);
                String subO2 = o2.getKey().substring(0, 1);
//                MyLog.e(object, "O!O2" + subO1 + subO2);
                return subO1.compareTo(subO2);
            }
        });
//        String url = "";
//        for (int i = 0; i < entryList.size(); i++) {
//            String key = entryList.get(i).getKey();
//            String value = (String) entryList.get(i).getValue();
//            url += key + value;
//        }
//        MyLog.e(object, "参数名和参数值拼接:" + url);
//        Log.e("netUtils------->", url);
//        String name = StringUtils.strToMD5("33445d8b31fa81b444f3b8263c47dbfc" + url + "33445d8b31fa81b444f3b8263c47dbfc");
//
        params.put("sign", MD5Util.getMD5Post(params));

        PostFormBuilder builder = OkHttpUtils.post()
                .url("https://test.c.api.kkpbcdn.com/gateway?");
        Iterator<Map.Entry<String, Object>> iterator = params.entrySet().iterator();

//        添加参数
        while (iterator.hasNext()) {
            Map.Entry<String, Object> next = iterator.next();
            String key = next.getKey();
            String value = (String) next.getValue();
            Log.e("请求参数： ",  key + " = " + value);
            builder.addParams(key, value);
        }
        builder.build().execute(callback);
    }

}
